﻿using LF.Domain.Helper;
using LF.Shared.Dtos.Out;
using System.Reflection;
using Volo.Abp.DependencyInjection;
using Volo.Abp.DynamicProxy;
using Volo.Abp.Uow;

namespace LF.Application.Aop
{
    /// <summary>
    /// 事务AOP
    /// 对应service 需要标记为 virtual 
    /// </summary>
    public class AppUnitOfWorkInterceptor : AbpInterceptor, ITransientDependency
    {

        public override Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            var service = invocation.TargetObject as IApplicationService;
            if (service != null)
            {

                var work = invocation.Method.GetCustomAttribute(typeof(UnitOfWorkAttribute));
                if (work != null)
                {
                    try
                    {
                        DbTransactionHelper.Start(() =>
                        {
                            invocation.ProceedAsync().Wait();
                        });
                    }
                    catch(Exception ex)
                    {
                        Serilog.Log.Error(ex, "事务失败 调用：" + ex.Message);
                        invocation.ReturnValue = new Result { Data = "异常:" + ex.Message, Code = Code.Error };
                    }
                }
                else
                {
                    _ = invocation.ProceedAsync();
                }
                
            }
            return Task.CompletedTask;
        }
    }
}
